package cn.edu.sjtu.blank.controller;

import cn.edu.sjtu.blank.dto.StateDTO;
import cn.edu.sjtu.blank.dto.TaskDTO;
import cn.edu.sjtu.blank.enums.ResultEnum;
import cn.edu.sjtu.blank.service.BlankService;
import cn.edu.sjtu.blank.util.ResultUtil;
import cn.edu.sjtu.blank.vo.ResultVO;
import cn.edu.sjtu.blank.vo.TaskVO;
import cn.edu.sjtu.blank.vo.TasksWithTypeVO;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author loumoon
 * @date 2019-11-29 15:19
 */
@RestController
public class BlankController {
  private final BlankService blankService;

  public BlankController(BlankService blankService) {
    this.blankService = blankService;
  }

  @PostMapping("/api/offer")
  public ResultVO addToTaskQueue(@RequestBody TaskDTO taskDTO) {
    blankService.addTaskToPool(taskDTO);
    return ResultUtil.success();
  }

  @GetMapping("/api/tasks")
  public ResultVO listTaskQueue() {
    //    List<TaskVO> taskVOQueue = flawDetectionService.listTaskQueue();
    //    return ResultUtil.success(taskVOQueue);
    Map<Integer, List<TaskVO>> map = blankService.retTasksPool();
    return ResultUtil.success(TasksWithTypeVO.build(map));
  }

  @PostMapping("/api/start")
  public ResultVO startTask(@RequestBody TaskDTO taskDTO) {
    boolean ret = blankService.startTask(taskDTO);
    if (ret) {
      return ResultUtil.success();
    }
    return ResultUtil.error(ResultEnum.TASK_START_ERROR);
  }

  @PostMapping("/api/end")
  public ResultVO endTask(@RequestBody TaskDTO taskDTO) {
    boolean ret = blankService.endTask(taskDTO);
    if (ret) {
      return ResultUtil.success();
    }
    return ResultUtil.error(ResultEnum.TASK_START_ERROR);
  }

  @GetMapping(
      value = "/api/state",
      params = {"processId", "taskId"})
  // TODO: 2019/12/25 don't do check
  public ResultVO getStatus(String processId, String taskId) {
    StateDTO stateDTO = blankService.queryTaskState(processId, taskId);
    return ResultUtil.success(stateDTO);
  }

  // state of ecn
  @GetMapping(value = "/api/state")
  public ResultVO getStatus() {
    StateDTO stateDTO = blankService.queryECNState();
    return ResultUtil.success(stateDTO);
  }

  @PostMapping("/api/input")
  public ResultVO inputData(@RequestBody JSONObject input) {
    // 接收来自人工任务的输入 这个输入可能是直接从前端输入 预留
    // 流程管理模块不调用该接口
    return ResultUtil.success();
  }
}
